<?php
class ContactController extends Core_Controller_Action
{
    public function indexAction() {
        require_once LIB_PATH . '/recaptchalib.php';
        $recaptcha_info = Core_Util::getConfig('recaptcha');
        $this->view->recaptcha_info = $recaptcha_info;
        
        if ( $this->getRequest()->isPost() ) {
            $resp = recaptcha_check_answer ($recaptcha_info['private_key'],
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

            if (!$resp->is_valid) {
                $this->view->message = array (
                    'status' => 0,
                    'message' => "The reCAPTCHA wasn't entered correctly"
                );
                $this->view->old_params = array (
                    'name' => $this->_getParam("name"),
                    'email' => $this->_getParam("email"),
                    'phone' => $this->_getParam("phone"),
                    'subject' => $this->_getParam("subject"),
                    'message' => $this->_getParam("message")
                );
            } else {
                $params = array (
                    'name' => $this->_getParam("name"),
                    'email' => $this->_getParam("email"),
                    'phone' => $this->_getParam("phone"),
                    'subject' => $this->_getParam("subject"),
                    'message' => $this->_getParam("message")
                );
                $this->_sendEmail($params);
                $this->view->message = array (
                    'status' => 1,
                    'message' => 'Your message was sent successfully. Thanks.'
                );
            }
        }
    }
    
    private function _sendEmail($params) {
        $config_db = new Core_Model_DbTable_Config();
        $email_configs = $config_db->getMailSettings();
        $config = array (
                    'auth' => 'login',
                    'username' => $email_configs['smtp_user'],
                    'password' => $email_configs['smtp_password'],
                    'ssl' => 'tls' 
                 );
 
        $transport = new Zend_Mail_Transport_Smtp($email_configs['smtp_host'], $config);
        
        $mail = new Zend_Mail('UTF-8'); 
        $mail->setBodyText($params['message']);
        $mail->setFrom($params['email'], $params['name'] . ' - ' . $params['phone']);
        $mail->addTo($email_configs['smtp_user'], '');
        $mail->setSubject($params['subject']);
        $mail->send($transport);
    }
}